import { reactive, inject } from "vue";
import { useRoleStore } from '../../../store/useRoleStore'

export const useRoleTable = (currentPage: any, pageSize: any) => {
    //获取API配置
    const API = inject("API") as any;
    const ApiConfig = inject("ApiConfig") as any;
    const roleTable = reactive(
        {
            total: 0,
            tableData: [],
            queryCondition: {
                roleName: '',
            }
        }
    );

    const roleStore = useRoleStore();

    //查询
    const queryData = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.POST,
                ApiConfig.PATH.Role.GetAllRole,
                {
                    pageIndex: currentPage.value,
                    pageSize: pageSize.value,
                    condition: { roleName: roleTable.queryCondition.roleName },
                }
            );
            if (response.status == "200" && response.data.code == "200") {
                roleTable.tableData = response.data.data;
                roleTable.total = response.data.count;
            }
        } catch (error) {
            console.error(error);
        }
    };
    //新增
    const addData = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.POST,
                ApiConfig.PATH.Role.Create,
                roleStore.roleModel
            );
            if (response.status == "200" && response.data.code == "200") {
                return true;
            }
        } catch (error) {
            console.error(error);
        }
        return false;
    }
    //更新
    const updateData = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.POST,
                ApiConfig.PATH.Role.Update,
                roleStore.roleModel
            );
            if (response.status == "200" && response.data.code == "200") {
                return true;
            }
        } catch (error) {
            console.error(error);
        }
        return false;
    }
    //删除
    const deleteData = async (userId) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Role.DeleteByRoleId,
                { 'userId': userId }
            );
            if (response.status == "200" && response.data.code == "200") {
                return true;
            }
        } catch (error) {
            console.error(error);
        }
        return false;
    }

    return { roleTable, roleStore, queryData, addData, updateData, deleteData };
};